package com.cn.goodsadmin.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.cn.goodsadmin.controller.LoginRequired;
import com.cn.goodsadmin.controller.SupplyMap;
import com.cn.goodsadmin.po.App;
import com.cn.goodsadmin.util.ErrorMsg;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (!(o instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        if (methodAnnotation != null) {
            HttpSession session = httpServletRequest.getSession(false);
            if (session != null) {
                App user = (App) session.getAttribute("user");
                if (user != null) {
                    return true;
                }else{
                    //没有登陆
                    sendSessionInvid(httpServletResponse);
                    return false;
                }
            }else{
                //sesion 过期
                sendSessionInvid(httpServletResponse);
                return false;
            }

        }
        //不需要登陆
        return true;
    }

    private void  sendSessionInvid(HttpServletResponse httpServletResponse)throws Exception {
        SupplyMap supplyMap=new SupplyMap();
        supplyMap.setEorrInfo(ErrorMsg.STATUS_SESSION_TIMEOUT,ErrorMsg.MSG_SESSION_TIMEOUT);
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter printWriter= httpServletResponse.getWriter();
        printWriter.print(JSONObject.toJSON(supplyMap));
    }


    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
